package com.fly.source.ui;

import java.awt.Dimension;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileFilter;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import com.fly.source.utils.Executor;
import com.fly.source.utils.MvnUtils;

import lombok.extern.slf4j.Slf4j;

/*****
 * 界面操作展示类
 */
@Slf4j
public class QuickSourceUI extends JFrame
{
    private static final long serialVersionUID = -9154321945329564644L;
    
    // 界面组件
    JPanel panel = new JPanel();
    
    JTextArea textArea = new JTextArea();
    
    JTextField fileText = new JTextField(null, 40);
    
    JButton fileDirBrowse = new JButton("请选择");
    
    JButton runButton = new JButton(" 获 取 源 码 包 ");
    
    // 构造函数
    public QuickSourceUI()
    {
        // 加载图标
        URL imgURL = getClass().getResource("/img/icon.gif");
        if (imgURL != null)
        {
            setIconImage(getToolkit().createImage(imgURL));
        }
        setTitle("POM源码工具 V1.0");
        setSize(1000, 800);
        Dimension screenSize = getToolkit().getScreenSize();
        Dimension frameSize = this.getSize();
        frameSize.height = Math.min(screenSize.height, frameSize.height);
        frameSize.width = Math.min(screenSize.width, frameSize.width);
        setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
        addMenu();
        addButton();
        copyPomFromJar();
        try
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            SwingUtilities.updateComponentTreeUI(this);
        }
        catch (Exception e)
        {
        }
        setResizable(false);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        fileText.setFocusable(false);
    }
    
    /**
     * jar 拷贝样例pom
     * 
     * @throws IOException
     * 
     */
    private void copyPomFromJar()
    {
        URL url = QuickSourceUI.class.getProtectionDomain().getCodeSource().getLocation();
        if (url.getPath().endsWith(".jar"))
        {
            try (InputStream is = QuickSourceUI.class.getResourceAsStream("/pom.xml"))
            {
                File file = new File(DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd-HHmmss") + "-pom.xml");
                FileUtils.copyInputStreamToFile(is, file);
                file.deleteOnExit();
            }
            catch (IOException e)
            {
                log.error(e.getMessage(), e);
            }
        }
    }
    
    // Menu set
    private void addMenu()
    {
        JMenuBar mb = new JMenuBar();
        // 一级菜单
        JMenu conf = new JMenu(" 系 统 ");
        // 子菜单
        JMenuItem exit = new JMenuItem("退出");
        exit.addActionListener(event -> System.exit(0));
        conf.add(exit);
        mb.add(conf);
        JMenu help = new JMenu(" 帮 助 ");
        JMenuItem about = new JMenuItem("关于工具");
        about.addActionListener((ActionEvent event) -> JOptionPane.showMessageDialog(null, "POM源码工具 V1.0，00fly 于2024年11月。\n", "关于本工具", JOptionPane.INFORMATION_MESSAGE));
        help.add(about);
        mb.add(help);
        setJMenuBar(mb);
    }
    
    // JButton set
    private void addButton()
    {
        panel.setLayout(null);
        getContentPane().add(panel);
        
        JLabel textLabel = new JLabel("pom文件内容");
        textLabel.setBounds(20, 10, 120, 18);
        panel.add(textLabel);
        
        JLabel fileLabel = new JLabel("POM文件");
        fileLabel.setBounds(30, 700, 240, 18);
        panel.add(fileLabel);
        
        textArea.setEditable(false);
        
        JScrollPane scroll = new JScrollPane(textArea);
        scroll.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        scroll.setBounds(20, 30, 950, 650);
        panel.add(scroll);
        
        fileText.setBounds(100, 700, 560, 24);
        fileText.setText(new File(" ").getAbsolutePath().trim());
        panel.add(fileText);
        fileDirBrowse.setBounds(680, 700, 80, 25);
        fileDirBrowse.addActionListener(event -> {
            String path = fileText.getText();
            File xmlfile = new File(path);
            if (new File(fileText.getText()).exists())
            {
                xmlfile = new File(path).getParentFile();
            }
            JFileChooser fc = new JFileChooser(xmlfile);
            fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fc.setDialogTitle("pom.xml文件选择");
            if (fc.showOpenDialog(null) == JFileChooser.CANCEL_OPTION)
            {
                return;
            }
            fc.setFileFilter(new FileFilter()
            {
                @Override
                public boolean accept(File file)
                {
                    return file.getName().toLowerCase().endsWith(".xml");
                }
                
                @Override
                public String getDescription()
                {
                    return "";
                }
            });
            File f = fc.getSelectedFile();
            if (f != null && f.isFile())
            {
                fileText.setText(f.getAbsolutePath());
                try
                {
                    textArea.setText(FileUtils.readFileToString(f, StandardCharsets.UTF_8));
                    runButton.setEnabled(true);
                }
                catch (IOException e)
                {
                }
            }
        });
        panel.add(fileDirBrowse);
        
        runButton.addMouseListener(new MouseAdapter()
        {
            @Override
            public void mouseClicked(MouseEvent e)
            {
                if (!runButton.isEnabled())
                {
                    return;
                }
                new Thread(() -> {
                    try
                    {
                        runButton.setText(" 处 理 中 ......");
                        runButton.setEnabled(false);
                        
                        // 业务处理
                        String pomPath = fileText.getText();
                        if (!new File(pomPath).exists())
                        {
                            throw new Exception(pomPath + "文件不存在");
                        }
                        
                        // 移动pom文件
                        File dest = new File("upload/pom.xml");
                        FileUtils.copyFile(new File(pomPath), dest);
                        
                        // 运行package命令，通过pom文件中的插件maven-dependency-plugin收集jar到lib
                        pomPath = dest.getCanonicalPath();
                        log.info("pom.xml 文件路径：{}", pomPath);
                        Executor.execute("mvn clean package -f " + pomPath).forEach(log::info);
                        // 收集sources
                        MvnUtils.copyResource(pomPath);
                        setExtendedState(Frame.ICONIFIED);
                        
                        runButton.setText(" 获 取 源 码 包 ");
                        runButton.setEnabled(true);
                    }
                    catch (Exception e1)
                    {
                        JOptionPane.showMessageDialog(null, "失败原因： " + e1.getMessage(), "业务处理失败", JOptionPane.ERROR_MESSAGE);
                    }
                }).start();
            }
        });
        runButton.setBounds(780, 695, 160, 30);
        runButton.setEnabled(false);
        panel.add(runButton);
    }
    
    // Run
    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(() -> new QuickSourceUI());
    }
}
